﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using WFNetLib;
using System.IO;
using Microsoft.Office.Interop.Excel;

namespace QueryBookTicket
{
    public partial class Form1 : Form
    {       
        System.Windows.Forms.Button[] btnCOMs;
        System.Windows.Forms.TextBox[] txCOMs;
        SerialPort[] COMs;
        string file="";
        public Form1()
        {
            InitializeComponent();
            btnCOMs = new System.Windows.Forms.Button[16];
            txCOMs = new System.Windows.Forms.TextBox[16];
            COMs = new SerialPort[16];
            for(int i=0;i<16;i++)
            {
                btnCOMs[i] = new System.Windows.Forms.Button();
                txCOMs[i] = new System.Windows.Forms.TextBox();
            }
            splitContainer8.Panel1.Controls.Add(txCOMs[0]);
            splitContainer8.Panel2.Controls.Add(txCOMs[1]);
            splitContainer9.Panel1.Controls.Add(txCOMs[2]);
            splitContainer9.Panel2.Controls.Add(txCOMs[3]);
            splitContainer10.Panel1.Controls.Add(txCOMs[4]);
            splitContainer10.Panel2.Controls.Add(txCOMs[5]);
            splitContainer11.Panel1.Controls.Add(txCOMs[6]);
            splitContainer11.Panel2.Controls.Add(txCOMs[7]);
            splitContainer12.Panel1.Controls.Add(txCOMs[8]);
            splitContainer12.Panel2.Controls.Add(txCOMs[9]);
            splitContainer13.Panel1.Controls.Add(txCOMs[10]);
            splitContainer13.Panel2.Controls.Add(txCOMs[11]);
            splitContainer14.Panel1.Controls.Add(txCOMs[12]);
            splitContainer14.Panel2.Controls.Add(txCOMs[13]);
            splitContainer15.Panel1.Controls.Add(txCOMs[14]);
            splitContainer15.Panel2.Controls.Add(txCOMs[15]);

            splitContainer8.Panel1.Controls.Add(btnCOMs[0]);
            splitContainer8.Panel2.Controls.Add(btnCOMs[1]);
            splitContainer9.Panel1.Controls.Add(btnCOMs[2]);
            splitContainer9.Panel2.Controls.Add(btnCOMs[3]);
            splitContainer10.Panel1.Controls.Add(btnCOMs[4]);
            splitContainer10.Panel2.Controls.Add(btnCOMs[5]);
            splitContainer11.Panel1.Controls.Add(btnCOMs[6]);
            splitContainer11.Panel2.Controls.Add(btnCOMs[7]);
            splitContainer12.Panel1.Controls.Add(btnCOMs[8]);
            splitContainer12.Panel2.Controls.Add(btnCOMs[9]);
            splitContainer13.Panel1.Controls.Add(btnCOMs[10]);
            splitContainer13.Panel2.Controls.Add(btnCOMs[11]);
            splitContainer14.Panel1.Controls.Add(btnCOMs[12]);
            splitContainer14.Panel2.Controls.Add(btnCOMs[13]);
            splitContainer15.Panel1.Controls.Add(btnCOMs[14]);
            splitContainer15.Panel2.Controls.Add(btnCOMs[15]);

            
            for(int i=0;i<16;i++)
            {
                btnCOMs[i].Dock=DockStyle.Top;
                btnCOMs[i].Name="btnCOM"+(i+3).ToString();
                btnCOMs[i].Text="COM"+(i+3).ToString()+"---等待";
                btnCOMs[i].UseVisualStyleBackColor=true;
                btnCOMs[i].Click+=new System.EventHandler(btnClick);
                btnCOMs[i].Tag = i;
                btnCOMs[i].BackColor = Color.Green;
                btnCOMs[i].Font = new System.Drawing.Font("宋体", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                btnCOMs[i].Height = 40;

                txCOMs[i].Dock=DockStyle.Fill;
                txCOMs[i].Multiline=true;
                txCOMs[i].Name="txCOM"+(i+3).ToString();
                txCOMs[i].ScrollBars = System.Windows.Forms.ScrollBars.Vertical;


                COMs[i] = new SerialPort("COM"+(i+3).ToString(), 115200);
                COMs[i].Handshake = Handshake.RequestToSend;
                COMs[i].DtrEnable = true;
                COMs[i].PortName = "COM1";
            }
            QueryBookTicketThread1.AddLogEvent += new WFNetLib.strEventHandler(QueryBookTicketThread1_AddLogEvent);
            QueryBookTicketThread1.FinishEvent += new intstrEventHandler(QueryBookTicketThread1_FinishEvent);
            file = System.Windows.Forms.Application.StartupPath + "\\TextLog\\" + "书券.txt";
            FileInfo f = new FileInfo(file);
            if (!Directory.Exists(f.DirectoryName))
                Directory.CreateDirectory(f.DirectoryName);
            if (!File.Exists(file))
            {
                FileStream fs = new FileStream(file, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                //开始写入
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("{0,-16}", "手机号码");
                sb.AppendFormat("{0,-15}", "书券");
                fs.Seek(0, SeekOrigin.End);
                sw.WriteLine(sb.ToString());
                //清空缓冲区
                sw.Flush();
                //关闭流
                sw.Close();
                fs.Close();/**/
            }
        }
        private void btnClick(object sender, EventArgs e)
        {
            int btnInex = (int)((System.Windows.Forms.Button)sender).Tag;
            if (btnCOMs[btnInex].BackColor == Color.Yellow)//等待中
                return;
            else
            {
                txCOMs[btnInex].Clear();
                QueryBookTicketThread1 read = new QueryBookTicketThread1(COMs[btnInex],btnInex);
                read.ReaderThreadStart();
                btnCOMs[btnInex].BackColor = Color.Yellow;
                btnCOMs[btnInex].Text = "COM" + (btnInex + 3).ToString() + "---查询中";                
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 16; i++)
            {
                btnClick(btnCOMs[i], new EventArgs());
            }
        }
        void QueryBookTicketThread1_AddLogEvent(object sender, strEventArgs e)
        {
            this.Invoke((EventHandler)(delegate
            {
                QueryBookTicketThread1 read = (QueryBookTicketThread1)sender;
                txCOMs[read.ComIndex].AppendText(e.strArg + "\r\n"); 
            }));
        }
        void QueryBookTicketThread1_FinishEvent(object sender, intstrEventArgs e)
        {
            this.Invoke((EventHandler)(delegate
            {
                QueryBookTicketThread1 read = (QueryBookTicketThread1)sender;
                FinishType ft = (FinishType)e.nArg;
                switch (ft)
                {
                    case FinishType.Finish:
                        btnCOMs[read.ComIndex].Text = "COM" + (read.ComIndex+3).ToString() + "---查询成功";
                        btnCOMs[read.ComIndex].BackColor = Color.Green;
                        string[] ret = e.strArg.Split(';');
                        FileStream fs = new FileStream(file, FileMode.Open);
                        StreamWriter sw = new StreamWriter(fs);
                        //开始写入
                        StringBuilder sb = new StringBuilder();
                        sb.AppendFormat("{0,-20}", ret[0]);
                        sb.AppendFormat("{0,-15}", ret[1]);
                        fs.Seek(0, SeekOrigin.End);
                        sw.WriteLine(sb.ToString());
                        //清空缓冲区
                        sw.Flush();
                        //关闭流
                        sw.Close();
                        fs.Close();/**/
                        break;                    
                    case FinishType.Unkown:
                        btnCOMs[read.ComIndex].Text = "COM" + (read.ComIndex+3).ToString() + "---网页连接错误，请重新查询";
                        btnCOMs[read.ComIndex].BackColor = Color.Red;
                        break;
                    case FinishType.UnkownTicket:
                        btnCOMs[read.ComIndex].Text = "COM" + (read.ComIndex+3).ToString() + "---未知书券，请重新查询";
                        btnCOMs[read.ComIndex].BackColor = Color.Red;
                        break;
                }
            }));
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认清除历史数据?", "警告", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                return;
            FileStream fs = new FileStream(file, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0,-16}", "手机号码");
            sb.AppendFormat("{0,-15}", "书券");
            fs.Seek(0, SeekOrigin.End);
            sw.WriteLine(sb.ToString());
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();/**/
            MessageBox.Show("清除历史数据成功");
        }
        ExcelExport ep;
        StreamReader sw;
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream(file, FileMode.Open);
            sw = new StreamReader(fs);
            sw.ReadLine();
            ep = new ExcelExport();
            ep.ExcelWorkbookCallbackProc = new ExcelExport.ExcelWorkbookCallback(ExcelWorkbookCallbackProc);
            ep.ExcelExportProc();
        }
        private bool ExcelWorkbookCallbackProc(Workbook wBook, int index)
        {
            Worksheet wSheet = (Worksheet)wBook.Worksheets[wBook.Worksheets.Count];
            Range dr;
            if (index == -1)
            {
                wSheet.Name = "书券";
                wSheet.Cells[1, 1] = "手机号码";
                wSheet.Cells[1, 2] = "书券";
                dr = wSheet.get_Range("A1", "B1");
                dr.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.DarkOrange);
                dr.Interior.Pattern = XlPattern.xlPatternSolid;
            }
            else if (index == int.MaxValue)
            {
                dr = wSheet.get_Range("A1", "B" + (ep.Count).ToString());
                dr.Columns.AutoFit();
                dr.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                dr.Borders.LineStyle = XlLineStyle.xlContinuous;
            }
            else
            {
                if (sw.Peek() >= 0)
                {
                    string[] str = sw.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                    wSheet.Cells[2 + index, 1] = str[0];
                    wSheet.Cells[2 + index, 2] = str[1];
                    if (index % 2 == 1)
                    {
                        dr = wSheet.get_Range("A" + (2 + index).ToString(), "B" + (2 + index).ToString());
                        dr.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
                        dr.Interior.Pattern = XlPattern.xlPatternSolid;
                    }
                }
                else
                {
                    sw.Close();
                    return false;
                }
            }
            return true;
        }
    }
}
